<template>
	<view class="search-page">
		<!-- 顶部导航栏 -->
		<view class="nav-bar">
			<view class="nav-left" @click="goBack">
				<icon type="back" size="20" color="#333"></icon>
			</view>
			<view class="nav-title">搜索</view>
			<view class="nav-right"></view>
		</view>

		<!-- 搜索栏 -->
		<view class="search-bar">
			<view class="search-container">
				<icon type="search" size="18" color="#999"></icon>
				<input class="search-input" placeholder="搜索帖子、用户或话题" confirm-type="search" v-model="searchKeyword"
					@confirm="handleSearch" />
				<!-- 搜索加载动画 -->
				<view v-if="searchLoading" class="loading-spinner">
					<view class="spinner"></view>
				</view>
			</view>
		</view>

		<!-- 搜索结果为空提示 -->
		<view v-if="searchResultList.length === 0 && searchKeyword && !searchLoading && !loadingMore" class="no-result">
			<text>未找到相关结果</text>
		</view>

		<!-- 搜索结果列表 -->
		<view v-if="searchKeyword && searchResultList.length > 0" class="search-results">
			<view class="result-title">搜索结果</view>
			<view v-for="(item, index) in searchResultList" :key="item.id" class="post-card"
				@click="goToPostDetail(item)">
				<!-- 用户信息 -->
				<view class="post-header">
					<view class="user-info">
						<!-- 匿名用户显示匿名头像和昵称 -->
						<view v-if="item.isAnonymous != -1" class="user-avatar-container">
							<image
								:src="item.niMingTouimg || 'https://paole.hebeixiaoyu.cn/run/profile/upload/nimingtouxiang.png'"
								class="avatar">
							</image>
							<text class="username">{{ item.niMingName || '神秘同学' }}</text>
						</view>
						<!-- 非匿名用户显示普通头像和昵称 -->
						<view v-else class="user-avatar-container">
							<image :src="item.avatarText || '/static/image/default-avatar.png'" class="avatar"></image>
							<text class="username">{{ item.username || '未知用户' }}</text>
						</view>
					</view>
					<text class="time">{{ formatTime(item.createTime) }}</text>
				</view>

				<!-- 帖子内容 -->
				<view class="post-content">
					<text class="desc">{{ item.content }}</text>
				</view>

				<!-- 互动数据 -->
				<view class="post-footer">
					<view class="interaction">
						<view class="like-btn">
							<image
								:src="item.likestatus === 1 ? 'https://paole.hebeixiaoyu.cn/run/profile/upload/dianzanhongse.png' : 'https://paole.hebeixiaoyu.cn/run/profile/upload/dianzanheise.png'"
								mode="aspectFit"
								:style="{width: '36rpx', height: '36rpx', color: item.likestatus === 1 ? '#e5404f' : '#999'}" />

							<text>{{ item.likeCount || 0 }}</text>
						</view>
						<view class="comment-btn">
							<image src="https://paole.hebeixiaoyu.cn/run/profile/upload/pinglunheise.png"
								mode="aspectFit" :style="{width: '36rpx', height: '36rpx', color: '#3c91ff'}" />
							<text>{{ item.commentCount || 0 }}</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 加载更多提示 -->
			<view v-if="loadingMore" class="loading-more">
				<view class="spinner"></view>
				<text>加载更多</text>
			</view>
			<view v-if="!loadingMore && !hasMore && searchResultList.length > 0" class="no-more">
				<text>没有更多内容了</text>
			</view>
		</view>

		<!-- 默认显示热榜 -->
		<view v-if="!searchKeyword" class="hot-section">
			<!-- 热榜标题 -->
			<view class="section-title">
				<text class="title-text" style="color: #f58e24;">今日热榜</text>
			</view>

			<!-- 热榜列表 -->
			<view class="hot-list">
				<view class="hot-item" v-for="(item, index) in hotList" :key="item.id" @click="goToPostDetail(item)">
					<!-- 排名标识 -->
					<view class="rank-tag {{index < 3 ? 'top' + (index + 1) : ''}}">
						{{index + 1}}
					</view>

					<!-- 帖子内容 -->
					<view class="post-content">
						<view class="post-desc">
							{{item.content}}
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		onUnmounted,
		watch
	} from 'vue';
	import {
		getHotList,
		searchPosts,
		getSouSuo
	} from '@/api/xiaoquan.js';

	// 页面数据
	const schoolId = ref(uni.getStorageSync('school_id') || '5');
	const hotList = ref([]);
	const searchKeyword = ref('');
	const searchLoading = ref(false);
	const searchResultList = ref([]);

	// 分页相关数据
	const page = ref(1);
	const pageSize = ref(10);
	const totalPages = ref(0);
	const hasMore = ref(true);
	const loadingMore = ref(false);
	const timer = ref(null);

	// 加载热榜数据
	const loadHotList = async () => {
		try {
			const response = await getHotList(schoolId.value);
			hotList.value = response.data || [];
		} catch (error) {
			console.error('获取热榜数据失败', error);
		}
	};

	// 搜索处理 - 重置分页并加载第一页
	const handleSearch = async () => {
		if (!searchKeyword.value.trim()) return;

		// 重置分页状态
		page.value = 1;
		searchResultList.value = [];
		hasMore.value = true;

		try {
			searchLoading.value = true;
			const response = await getSouSuo(page.value, pageSize.value, schoolId.value, searchKeyword.value
				.trim());

			// 处理搜索结果
			if (response.data && response.data.length > 0) {
				searchResultList.value = response.data;

				// 假设API返回了总页数或总记录数，这里需要根据实际API响应调整
				// 示例：假设response.totalPages存在
				totalPages.value = response.totalPages || Math.ceil(response.totalCount / pageSize.value);
				hasMore.value = page.value < totalPages.value;
			} else {
				hasMore.value = false;
			}
		} catch (error) {
			console.error('搜索失败', error);
			uni.showToast({
				title: '搜索失败，请稍后重试',
				icon: 'none'
			});
		} finally {
			searchLoading.value = false;
		}
	};

	// 加载更多搜索结果
	const loadMore = async () => {
		if (!hasMore.value || loadingMore.value || !searchKeyword.value.trim()) return;

		page.value++;
		loadingMore.value = true;

		try {
			const response = await getSouSuo(page.value, pageSize.value, schoolId.value, searchKeyword.value
				.trim());

			if (response.data && response.data.length > 0) {
				// 合并新数据到现有列表
				searchResultList.value = [...searchResultList.value, ...response.data];

				// 更新是否有更多数据的状态
				hasMore.value = page.value < totalPages.value;
			} else {
				hasMore.value = false;
			}
		} catch (error) {
			console.error('加载更多失败', error);
			uni.showToast({
				title: '加载更多失败，请稍后重试',
				icon: 'none'
			});

			// 加载失败时回退页码
			page.value--;
		} finally {
			loadingMore.value = false;
		}
	};

	// 监听滚动事件实现无限加载
	const handleScroll = () => {
		// 获取页面高度和滚动距离
		const systemInfo = uni.getSystemInfoSync();
		const scrollTop = uni.createSelectorQuery().select('.search-page').boundingClientRect();
		const scrollHeight = systemInfo.windowHeight;

		// 当滚动到距离底部100px时触发加载更多
		scrollTop.exec((res) => {
			if (res[0].bottom <= scrollHeight + 100) {
				loadMore();
			}
		});
	};

	// 优化滚动监听，使用定时器减少触发频率
	const debounceScroll = () => {
		if (timer.value) clearTimeout(timer.value);
		timer.value = setTimeout(handleScroll, 300);
	};

	// 返回上一页
	const goBack = () => {
		uni.navigateBack();
	};

	// 格式化时间
	const formatTime = (time) => {
		const now = new Date();
		const postTime = new Date(time);
		const diffHours = Math.floor((now - postTime) / (1000 * 60 * 60));

		if (diffHours < 1) {
			return '刚刚';
		} else if (diffHours < 24) {
			return `${diffHours}小时前`;
		} else {
			return `${Math.floor(diffHours / 24)}天前`;
		}
	};

	// 前往帖子详情
	const goToPostDetail = (item) => {
		// console.log(item, "-----------")
		// 把点击的帖子基本信息村起来。
		uni.setStorageSync("itemDetail", item)
		// console.log(uni.getStorageSync("itemDetail"))
		uni.navigateTo({
			url: `/package/pages/postDetail/postDetail?id=${item.id}`
		});
	};

	// 页面加载时获取数据
	onMounted(() => {
		loadHotList();

		// 监听页面滚动事件
		uni.onPageScroll(debounceScroll);
	});

	// 页面卸载时移除滚动监听
	onUnmounted(() => {
		uni.offPageScroll(debounceScroll);
		if (timer.value) clearTimeout(timer.value);
	});

	// 监听搜索关键词变化
	watch(searchKeyword, (newVal, oldVal) => {
		if (newVal !== oldVal && newVal.trim()) {
			handleSearch();
		}
	});
</script>

<style>
	.search-page {
		padding: 0 20rpx 20rpx;
		background-color: #f8f8f8;
		min-height: 100vh;
		box-sizing: border-box;
	}

	/* 导航栏样式 */
	.nav-bar {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 30rpx 0 20rpx;
		background-color: #f8f8f8;
		position: sticky;
		top: 0;
		z-index: 10;
	}

	.nav-left,
	.nav-right {
		width: 80rpx;
	}

	.nav-title {
		font-size: 36rpx;
		font-weight: 600;
		color: #333;
		text-align: center;
		flex: 1;
	}

	/* 搜索栏样式 */
	.search-bar {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
		padding: 0 10rpx;
	}

	.search-container {
		flex: 1;
		display: flex;
		align-items: center;
		background-color: #fff;
		border-radius: 40rpx;
		padding: 16rpx 30rpx;
		margin-right: 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
		border: 1rpx solid #eee;
		position: relative;
	}

	.search-container icon {
		margin-right: 10rpx;
	}

	.search-input {
		flex: 1;
		font-size: 28rpx;
		color: #333;
		height: 50rpx;
	}

	/* 加载动画 */
	.loading-spinner {
		position: absolute;
		right: 20rpx;
		top: 50%;
		transform: translateY(-50%);
	}

	.spinner {
		width: 30rpx;
		height: 30rpx;
		border: 3rpx solid #409eff;
		border-top: 3rpx solid transparent;
		border-radius: 50%;
		animation: spin 1s linear infinite;
		display: inline-block;
		vertical-align: middle;
		margin-right: 10rpx;
	}

	@keyframes spin {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}

	/* 加载更多样式 */
	.loading-more {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 20rpx 0;
		color: #999;
		font-size: 28rpx;
	}

	.no-more {
		text-align: center;
		padding: 20rpx 0;
		color: #999;
		font-size: 28rpx;
	}

	/* 无结果提示 */
	.no-result {
		padding: 40rpx;
		text-align: center;
		color: #999;
		font-size: 28rpx;
		background-color: #fff;
		border-radius: 16rpx;
		margin: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	/* 搜索结果样式 */
	.search-results {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 0 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		margin: 0 10rpx;
	}

	.result-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
		padding: 25rpx 0 15rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	/* 帖子卡片样式 */
	.post-card {
		padding: 30rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.post-card:last-child {
		border-bottom: none;
	}

	.post-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 20rpx;
	}

	.user-info {
		display: flex;
		align-items: center;
	}

	.user-avatar-container {
		display: flex;
		align-items: center;
	}

	.avatar {
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		margin-right: 15rpx;
	}

	.username {
		font-size: 26rpx;
		font-weight: 500;
		color: #333;
	}

	.time {
		font-size: 24rpx;
		color: #999;
	}

	.post-content .desc {
		font-size: 28rpx;
		color: #333;
		line-height: 1.5;
		margin-bottom: 20rpx;
		display: -webkit-box;
		-webkit-line-clamp: 3;
		-webkit-box-orient: vertical;
		overflow: hidden;
	}

	.post-footer {
		display: flex;
		justify-content: flex-end;
	}

	.interaction {
		display: flex;
		align-items: center;
		gap: 30rpx;
	}

	.like-btn,
	.comment-btn {
		display: flex;
		align-items: center;
		gap: 8rpx;
		font-size: 24rpx;
		color: #999;
	}

	/* 热榜部分样式 */
	.hot-section {
		margin-top: 10rpx;
		background: linear-gradient(to right, #e6ffe8, #ffefea);
		border-radius: 16rpx;
		padding: 20rpx 0;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		margin: 10rpx;
	}

	/* section标题样式 */
	.section-title {
		padding: 0 30rpx 20rpx;
		font-size: 36rpx;
		font-weight: 700;
		color: #333;
		border-bottom: 1rpx solid #f0f0f0;
		margin-bottom: 10rpx;
	}

	/* 热榜列表样式 */
	.hot-list {
		border-radius: 16rpx;
		overflow: hidden;
	}

	.hot-item {
		display: flex;
		padding: 25rpx 30rpx;
		align-items: center;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.hot-item:last-child {
		border-bottom: none;
	}

	.rank-tag {
		width: 50rpx;
		height: 50rpx;
		border-radius: 8rpx;
		background-color: #f5f5f5;
		color: #999;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		font-weight: 600;
		margin-right: 20rpx;
		flex-shrink: 0;
	}

	.rank-tag.top1 {
		background-color: #ff4d4f;
		color: #fff;
	}

	.rank-tag.top2 {
		background-color: #ffa940;
		color: #fff;
	}

	.rank-tag.top3 {
		background-color: #ffd666;
		color: #fff;
	}

	.post-content {
		flex: 1;
		overflow: hidden;
	}

	.post-desc {
		font-size: 30rpx;
		color: #333;
		font-weight: 500;
		line-height: 1.4;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}
</style>